<template>
  <div class="case-library">
    <div class="page-header">
      <h1 class="page-title">案例库管理</h1>
      <div class="header-actions">
        <el-button type="warning" @click="goToCaseReview">
          <i class="fas fa-tasks mr-2"></i>案件审查流程
        </el-button>
        <el-button type="info" @click="goToAutoDemo">
          <i class="fas fa-play-circle mr-2"></i>查看自动入库演示
        </el-button>
        <el-button type="primary" @click="refreshData">
          <i class="fas fa-sync-alt mr-2"></i>刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <div class="search-row">
        <el-input
          v-model="searchQuery"
          placeholder="搜索案例标题、关键词或案例编号"
          class="search-input"
          clearable
        >
          <template #prefix>
            <i class="fas fa-search"></i>
          </template>
        </el-input>
        <el-select v-model="categoryFilter" placeholder="案例分类" clearable class="category-filter">
          <el-option label="全部" value=""></el-option>
          <el-option label="交通事故" value="traffic"></el-option>
          <el-option label="合同纠纷" value="contract"></el-option>
          <el-option label="劳动纠纷" value="labor"></el-option>
          <el-option label="房产纠纷" value="property"></el-option>
          <el-option label="医疗纠纷" value="medical"></el-option>
        </el-select>
        <el-select v-model="statusFilter" placeholder="状态" clearable class="status-filter">
          <el-option label="全部" value=""></el-option>
          <el-option label="已发布" value="published"></el-option>
          <el-option label="草稿" value="draft"></el-option>
          <el-option label="待审查" value="pending_review"></el-option>
          <el-option label="脱敏中" value="desensitizing"></el-option>
          <el-option label="人工审查" value="manual_review"></el-option>
          <el-option label="审核中" value="reviewing"></el-option>
        </el-select>
        <el-select v-model="tagFilter" placeholder="标签分类" clearable class="tag-filter">
          <el-option label="全部" value=""></el-option>
          <el-option label="判决" value="judgment"></el-option>
          <el-option label="调解" value="mediation"></el-option>
          <el-option label="和解" value="settlement"></el-option>
          <el-option label="撤诉" value="withdrawal"></el-option>
        </el-select>
        <el-select v-model="sensitiveFilter" placeholder="脱敏状态" clearable class="sensitive-filter">
          <el-option label="全部" value=""></el-option>
          <el-option label="已脱敏" value="desensitized"></el-option>
          <el-option label="待脱敏" value="pending_desensitization"></el-option>
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <div class="stat-card total">
        <div class="stat-icon">
          <i class="fas fa-folder-open"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.totalCases }}</div>
          <div class="stat-label">总案例数</div>
        </div>
      </div>
      <div class="stat-card published">
        <div class="stat-icon">
          <i class="fas fa-check-circle"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.publishedCases }}</div>
          <div class="stat-label">已发布</div>
        </div>
      </div>
      <div class="stat-card draft">
        <div class="stat-icon">
          <i class="fas fa-edit"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.draftCases }}</div>
          <div class="stat-label">草稿</div>
        </div>
      </div>
      <div class="stat-card pending">
        <div class="stat-icon">
          <i class="fas fa-clock"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.pendingReview }}</div>
          <div class="stat-label">待审查</div>
        </div>
      </div>
      <div class="stat-card views">
        <div class="stat-icon">
          <i class="fas fa-eye"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.totalViews }}</div>
          <div class="stat-label">总浏览量</div>
        </div>
      </div>
    </div>

    <!-- 案例列表 -->
    <div class="cases-section">
      <div class="section-header">
        <h2 class="section-title">案例列表</h2>
        <div class="view-controls">
          <el-radio-group v-model="viewMode" size="small">
            <el-radio-button label="table">表格视图</el-radio-button>
            <el-radio-button label="card">卡片视图</el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <!-- 表格视图 -->
      <div v-if="viewMode === 'table'" class="table-view">
        <el-table :data="filteredCases" v-loading="loading" style="width: 100%">
          <el-table-column prop="id" label="案例ID" width="80"></el-table-column>
          <el-table-column prop="title" label="案例标题" min-width="200">
            <template #default="{ row }">
              <div class="case-title">
                <span class="title-text">{{ row.title }}</span>
                <el-tag v-if="row.isRecommended" type="warning" size="small">推荐</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="category" label="分类" width="120">
            <template #default="{ row }">
              <el-tag :type="getCategoryType(row.category)">{{ getCategoryText(row.category) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="author" label="录入人" width="100"></el-table-column>
          <el-table-column prop="caseEndType" label="案件结果" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getCaseEndTypeColor(row.caseEndType)" size="small">
                {{ getCaseEndTypeText(row.caseEndType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="sensitiveStatus" label="脱敏状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getSensitiveStatusType(row.sensitiveStatus)" size="small">
                {{ getSensitiveStatusText(row.sensitiveStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="visibleTo" label="可见人" width="120">
            <template #default="{ row }">
              <div class="visible-to">
                <el-tag v-for="person in row.visibleTo" :key="person" size="small" class="mr-1">
                  {{ person }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="views" label="浏览量" width="80" align="center"></el-table-column>
          <el-table-column prop="createdAt" label="创建时间" width="120"></el-table-column>
          <el-table-column label="操作" width="250" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" @click="editCase(row)">
                <i class="fas fa-edit mr-1"></i>编辑
              </el-button>
              <el-button size="small" type="info" @click="viewCase(row)">
                <i class="fas fa-eye mr-1"></i>预览
              </el-button>
              <el-button size="small" type="warning" @click="manageVisibility(row)">
                <i class="fas fa-users mr-1"></i>可见性
              </el-button>
              <el-button 
                size="small" 
                :type="row.sensitiveStatus === 'desensitized' ? 'success' : 'warning'"
                @click="handleDesensitization(row)"
              >
                <i class="fas fa-shield-alt mr-1"></i>
                {{ row.sensitiveStatus === 'desensitized' ? '已脱敏' : '脱敏' }}
              </el-button>
              <el-button 
                v-if="row.status === 'pending_review' || row.status === 'desensitizing' || row.status === 'manual_review'"
                size="small" 
                type="primary" 
                @click="handleManualReview(row)"
              >
                <i class="fas fa-user-check mr-1"></i>人工审查
              </el-button>
              <el-button size="small" type="danger" @click="deleteCase(row)">
                <i class="fas fa-trash mr-1"></i>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 卡片视图 -->
      <div v-else class="card-view">
        <div class="cases-grid">
          <div 
            v-for="case_ in filteredCases" 
            :key="case_.id"
            class="case-card"
            :class="{ 'recommended': case_.isRecommended }"
          >
            <div class="case-header">
              <div class="case-meta">
                <span class="case-id">#{{ case_.id }}</span>
                <el-tag :type="getCategoryType(case_.category)" size="small">
                  {{ getCategoryText(case_.category) }}
                </el-tag>
              </div>
              <div class="case-status">
                <el-tag :type="getStatusType(case_.status)" size="small">
                  {{ getStatusText(case_.status) }}
                </el-tag>
                <el-tag v-if="case_.isRecommended" type="warning" size="small">推荐</el-tag>
              </div>
            </div>
            
            <div class="case-content">
              <h3 class="case-title">{{ case_.title }}</h3>
              <p class="case-summary">{{ case_.summary }}</p>
              
              <div class="case-tags">
                <el-tag 
                  v-for="tag in case_.tags" 
                  :key="tag" 
                  size="small" 
                  type="info"
                  class="tag-item"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>
            
            <div class="case-stats">
              <div class="stat-item">
                <i class="fas fa-eye"></i>
                <span>{{ case_.views }}</span>
              </div>
              <div class="stat-item">
                <i class="fas fa-heart"></i>
                <span>{{ case_.likes }}</span>
              </div>
              <div class="stat-item">
                <i class="fas fa-user"></i>
                <span>{{ case_.author }}</span>
              </div>
              <div class="stat-item">
                <i class="fas fa-calendar"></i>
                <span>{{ case_.createdAt }}</span>
              </div>
            </div>
            
            <div class="case-actions">
              <el-button size="small" type="primary" @click="editCase(case_)">
                <i class="fas fa-edit mr-1"></i>编辑
              </el-button>
              <el-button size="small" type="info" @click="viewCase(case_)">
                <i class="fas fa-eye mr-1"></i>预览
              </el-button>
              <el-button size="small" type="danger" @click="deleteCase(case_)">
                <i class="fas fa-trash mr-1"></i>删除
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 48, 96]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCases"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 案例库说明 -->
    <div class="library-info">
      <el-alert
        title="案例库数据来源说明"
        type="info"
        :closable="false"
        show-icon
      >
        <template #default>
          <p><strong>案例库中的所有案例均来自案件办结后的自动入库流程：</strong></p>
          <ol>
            <li>律师完成案件处理后，系统自动将案件信息加入案例库</li>
            <li>案例进入"待审查"阶段，等待系统脱敏处理</li>
            <li>AI自动识别并处理敏感信息（身份证、手机号等）</li>
            <li>管理人员审查脱敏结果，确认案例质量</li>
            <li>审查通过后，案例正式发布到案例库供查阅</li>
          </ol>
          <p class="mt-2">
            <el-button type="text" @click="goToCaseReview">
              <i class="fas fa-arrow-right mr-1"></i>前往案件审查流程管理
            </el-button>
          </p>
        </template>
      </el-alert>
    </div>

    <!-- 可见性管理对话框 -->
    <el-dialog v-model="showVisibilityDialog" title="管理案例可见性" width="600px">
      <div v-if="currentCase" class="visibility-management">
        <div class="case-info">
          <h4>案例：{{ currentCase.title }}</h4>
          <p class="case-meta">作者：{{ currentCase.author }} | 创建时间：{{ currentCase.createdAt }}</p>
        </div>
        
        <el-divider></el-divider>
        
        <div class="visibility-section">
          <h5>当前可见人员</h5>
          <div class="current-visibility">
            <el-tag 
              v-for="person in currentCase.visibleTo" 
              :key="person"
              closable
              @close="removeVisiblePerson(person)"
              class="mr-2 mb-2"
            >
              {{ person }}
            </el-tag>
          </div>
        </div>
        
        <div class="add-visibility">
          <h5>添加可见人员</h5>
          <el-select
            v-model="selectedPersons"
            multiple
            placeholder="选择人员或角色"
            style="width: 100%"
          >
            <el-option-group label="角色组">
              <el-option label="所有律师" value="所有律师"></el-option>
              <el-option label="高级管理员" value="高级管理员"></el-option>
              <el-option label="交通事故律师" value="交通事故律师"></el-option>
              <el-option label="保险理赔律师" value="保险理赔律师"></el-option>
              <el-option label="刑事律师" value="刑事律师"></el-option>
              <el-option label="伤残鉴定师" value="伤残鉴定师"></el-option>
            </el-option-group>
            <el-option-group label="具体人员">
              <el-option label="张律师" value="张律师"></el-option>
              <el-option label="李律师" value="李律师"></el-option>
              <el-option label="王律师" value="王律师"></el-option>
              <el-option label="陈律师" value="陈律师"></el-option>
              <el-option label="赵律师" value="赵律师"></el-option>
            </el-option-group>
          </el-select>
        </div>
        
        <div class="visibility-tips">
          <el-alert
            title="提示"
            type="info"
            :closable="false"
            show-icon
          >
            <template #default>
              <ul>
                <li>案例可见性控制谁能查看此案例的详细内容</li>
                <li>脱敏处理后的案例可以设置更广泛的可见范围</li>
                <li>待脱敏的案例建议限制可见范围</li>
                <li>角色组会包含该角色下的所有人员</li>
              </ul>
            </template>
          </el-alert>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showVisibilityDialog = false">取消</el-button>
          <el-button type="primary" @click="saveVisibility">保存设置</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 人工审查对话框 -->
    <el-dialog v-model="showManualReviewDialog" title="人工审查" width="800px">
      <div v-if="currentReviewCase" class="manual-review-container">
        <!-- 案例基本信息 -->
        <div class="review-case-info">
          <div class="case-header">
            <h3>{{ currentReviewCase.title }}</h3>
            <div class="case-meta">
              <el-tag :type="getCategoryType(currentReviewCase.category)" size="small">
                {{ getCategoryText(currentReviewCase.category) }}
              </el-tag>
              <el-tag :type="getStatusType(currentReviewCase.status)" size="small">
                {{ getStatusText(currentReviewCase.status) }}
              </el-tag>
              <el-tag :type="getSensitiveStatusType(currentReviewCase.sensitiveStatus)" size="small">
                {{ getSensitiveStatusText(currentReviewCase.sensitiveStatus) }}
              </el-tag>
            </div>
          </div>
          
          <div class="case-details">
            <p><strong>案例摘要：</strong>{{ currentReviewCase.summary }}</p>
            <p><strong>案件结果：</strong>
              <el-tag :type="getCaseEndTypeColor(currentReviewCase.caseEndType)" size="small">
                {{ getCaseEndTypeText(currentReviewCase.caseEndType) }}
              </el-tag>
            </p>
            <p><strong>作者：</strong>{{ currentReviewCase.author }}</p>
            <p><strong>创建时间：</strong>{{ currentReviewCase.createdAt }}</p>
            <p v-if="currentReviewCase.autoAddedAt"><strong>自动入库时间：</strong>{{ currentReviewCase.autoAddedAt }}</p>
          </div>
        </div>

        <el-divider></el-divider>

        <!-- 审查表单 -->
        <div class="review-form">
          <el-form :model="reviewForm" :rules="reviewRules" ref="reviewFormRef" label-width="120px">
            <el-form-item label="审查结果" prop="reviewResult">
              <el-radio-group v-model="reviewForm.reviewResult">
                <el-radio label="approved">
                  <i class="fas fa-check-circle text-green-500 mr-1"></i>审查通过
                </el-radio>
                <el-radio label="rejected">
                  <i class="fas fa-times-circle text-red-500 mr-1"></i>审查拒绝
                </el-radio>
                <el-radio label="needs_revision">
                  <i class="fas fa-edit text-yellow-500 mr-1"></i>需要修改
                </el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="审查意见" prop="reviewComment">
              <el-input
                v-model="reviewForm.reviewComment"
                type="textarea"
                rows="4"
                placeholder="请输入审查意见和建议..."
              ></el-input>
            </el-form-item>

            <el-form-item v-if="reviewForm.reviewResult === 'approved'" label="发布设置">
              <div class="publish-settings">
                <el-checkbox v-model="reviewForm.setAsRecommended">设为推荐案例</el-checkbox>
                <el-checkbox v-model="reviewForm.allowPublicView">允许公开查看</el-checkbox>
              </div>
            </el-form-item>

            <el-form-item v-if="reviewForm.reviewResult === 'needs_revision'" label="修改要求" prop="revisionRequirements">
              <el-checkbox-group v-model="reviewForm.revisionRequirements">
                <el-checkbox label="sensitive_info">敏感信息处理不当</el-checkbox>
                <el-checkbox label="content_quality">内容质量需要改善</el-checkbox>
                <el-checkbox label="legal_accuracy">法律条文需要核实</el-checkbox>
                <el-checkbox label="format_issue">格式规范需要调整</el-checkbox>
                <el-checkbox label="completeness">信息完整性不足</el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <el-form-item label="审查人员">
              <el-input v-model="reviewForm.reviewer" disabled placeholder="当前登录用户"></el-input>
            </el-form-item>
          </el-form>
        </div>

        <!-- 审查历史 -->
        <div v-if="currentReviewCase.reviewHistory && currentReviewCase.reviewHistory.length > 0" class="review-history">
          <el-divider></el-divider>
          <h4>审查历史</h4>
          <div class="history-timeline">
            <div 
              v-for="(history, index) in currentReviewCase.reviewHistory" 
              :key="index"
              class="history-item"
            >
              <div class="history-time">{{ history.reviewTime }}</div>
              <div class="history-content">
                <div class="history-header">
                  <span class="history-reviewer">{{ history.reviewer }}</span>
                  <el-tag 
                    :type="history.result === 'approved' ? 'success' : history.result === 'rejected' ? 'danger' : 'warning'" 
                    size="small"
                  >
                    {{ history.result === 'approved' ? '通过' : history.result === 'rejected' ? '拒绝' : '需修改' }}
                  </el-tag>
                </div>
                <div class="history-comment">{{ history.comment }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showManualReviewDialog = false">取消</el-button>
          <el-button type="primary" @click="submitReview" :loading="reviewSubmitting">
            <i class="fas fa-check mr-1"></i>提交审查结果
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'AdminCaseLibrary',
  setup() {
    const loading = ref(false)
    const searchQuery = ref('')
    const categoryFilter = ref('')
    const statusFilter = ref('')
    const tagFilter = ref('')
    const sensitiveFilter = ref('')
    const viewMode = ref('table')
    const currentPage = ref(1)
    const pageSize = ref(24)
    // 移除添加和导入对话框的状态
    const showVisibilityDialog = ref(false)
    const currentCase = ref(null)
    const selectedPersons = ref([])
    
    // 人工审查相关状态
    const showManualReviewDialog = ref(false)
    const currentReviewCase = ref(null)
    const reviewSubmitting = ref(false)
    const reviewForm = reactive({
      reviewResult: '',
      reviewComment: '',
      setAsRecommended: false,
      allowPublicView: false,
      revisionRequirements: [],
      reviewer: '管理员'
    })
    
    // 审查表单验证规则
    const reviewRules = {
      reviewResult: [{ required: true, message: '请选择审查结果', trigger: 'change' }],
      reviewComment: [{ required: true, message: '请输入审查意见', trigger: 'blur' }]
    }
    
    // 交通事故案例库统计
    const stats = reactive({
      totalCases: 1856,     // 交通事故案例总数
      publishedCases: 1589, // 已发布交通事故案例
      draftCases: 267,      // 草稿交通事故案例
      pendingReview: 28,    // 待审查案例
      totalViews: 126892    // 交通事故案例浏览量
    })
    
    // 交通事故专业案例库
    const cases = ref([
      {
        id: 1,
        title: '多车连环追尾事故责任认定分析',
        category: 'traffic',
        author: '李卫民律师',
        status: 'published',
        caseEndType: 'judgment',
        sensitiveStatus: 'desensitized',
        visibleTo: ['所有律师', '高级管理员'],
        views: 3256,
        likes: 198,
        createdAt: '2024-02-15',
        summary: '分析世纪大道5车连环追尾事故中的责任认定原则和赔偿问题...',
        tags: ['多车事故', '责任认定', '连环追尾'],
        isRecommended: true,
        autoAddedAt: '2024-02-15 18:30:00'
      },
      {
        id: 2,
        title: '九级伤残赔偿标准及计算方法',
        category: 'traffic',
        author: '张医法律师',
        status: 'published',
        caseEndType: 'mediation',
        sensitiveStatus: 'desensitized',
        visibleTo: ['交通事故律师', '伤残鉴定师'],
        views: 4521,
        likes: 278,
        createdAt: '2024-02-12',
        summary: '详解交通事故九级伤残的认定标准和28万元赔偿计算...',
        tags: ['伤残鉴定', '九级伤残', '赔偿计算'],
        isRecommended: true,
        autoAddedAt: '2024-02-12 14:20:00'
      },
      {
        id: 3,
        title: '保险公司拒赔案例分析',
        category: 'traffic',
        author: '王志强律师',
        status: 'published',
        caseEndType: 'settlement',
        sensitiveStatus: 'desensitized',
        visibleTo: ['保险理赔律师'],
        views: 2867,
        likes: 165,
        createdAt: '2024-02-10',
        summary: '平安保险拒绝理赔案例中的法律争议点和应对策略...',
        tags: ['保险理赔', '拒赔争议', '维权策略'],
        isRecommended: false,
        autoAddedAt: '2024-02-10 16:45:00'
      },
      {
        id: 4,
        title: '交通肇事罪软判成功案例',
        category: 'traffic',
        author: '陈红律师',
        status: 'published',
        caseEndType: 'judgment',
        sensitiveStatus: 'desensitized',
        visibleTo: ['刑事律师', '高级管理员'],
        views: 1956,
        likes: 124,
        createdAt: '2024-02-08',
        summary: '某酒驾致死案中的刑事软判策略和法庭辩护技巧...',
        tags: ['交通肇事罪', '刑事辩护', '软判策略'],
        isRecommended: true,
        autoAddedAt: '2024-02-08 11:30:00'
      },
      {
        id: 5,
        title: '横穿马路事故责任划分',
        category: 'traffic',
        author: '刘建国律师',
        status: 'pending_review',
        caseEndType: 'judgment',
        sensitiveStatus: 'pending_desensitization',
        visibleTo: ['待审核'],
        views: 0,
        likes: 0,
        createdAt: '2024-02-16',
        summary: '行人横穿马路与机动车相撞的责任分担问题...',
        tags: ['横穿马路', '责任划分', '行人事故'],
        isRecommended: false,
        autoAddedAt: '2024-02-16 09:15:00'
      },
      {
        id: 6,
        title: '电动车交通事故特殊处理',
        category: 'traffic',
        author: '赵美华律师',
        status: 'desensitizing',
        caseEndType: 'mediation',
        sensitiveStatus: 'pending_desensitization',
        visibleTo: ['审核管理员'],
        views: 0,
        likes: 0,
        createdAt: '2024-02-14',
        summary: '电动车与传统机动车交通事故的法律适用差异...',
        tags: ['电动车', '新类型事故', '法律适用'],
        isRecommended: true,
        autoAddedAt: '2024-02-14 13:20:00'
      },
      {
        id: 7,
        title: '重大交通事故人身损害赔偿案',
        category: 'traffic',
        author: '孙律师',
        status: 'manual_review',
        caseEndType: 'judgment',
        sensitiveStatus: 'desensitized',
        visibleTo: ['审核管理员', '高级律师'],
        views: 0,
        likes: 0,
        createdAt: '2024-02-12',
        summary: '高速公路重大交通事故，造成3死2伤，涉及多方责任认定和巨额赔偿...',
        tags: ['重大事故', '人身损害', '高速公路'],
        isRecommended: false,
        autoAddedAt: '2024-02-12 16:30:00',
        reviewHistory: [
          {
            reviewTime: '2024-02-13 10:30:00',
            reviewer: '管理员',
            result: 'needs_revision',
            comment: '案例中涉及的敏感信息处理不够完善，需要进一步脱敏处理。'
          }
        ]
      }
    ])
    
    // 移除手动添加案例的表单数据和验证规则
    
    const filteredCases = computed(() => {
      return cases.value.filter(case_ => {
        const matchesSearch = !searchQuery.value || 
          case_.title.includes(searchQuery.value) ||
          case_.summary.includes(searchQuery.value) ||
          case_.tags.some(tag => tag.includes(searchQuery.value))
        
        const matchesCategory = !categoryFilter.value || case_.category === categoryFilter.value
        const matchesStatus = !statusFilter.value || case_.status === statusFilter.value
        const matchesTag = !tagFilter.value || case_.caseEndType === tagFilter.value
        const matchesSensitive = !sensitiveFilter.value || case_.sensitiveStatus === sensitiveFilter.value
        
        return matchesSearch && matchesCategory && matchesStatus && matchesTag && matchesSensitive
      })
    })
    
    const totalCases = computed(() => filteredCases.value.length)
    
    const getCategoryType = (category) => {
      const types = {
        'contract': 'primary',
        'traffic': 'danger',
        'labor': 'warning',
        'property': 'success',
        'medical': 'info'
      }
      return types[category] || 'info'
    }
    
    const getCategoryText = (category) => {
      const texts = {
        'contract': '合同纠纷',
        'traffic': '交通事故',
        'labor': '劳动纠纷',
        'property': '房产纠纷',
        'medical': '医疗纠纷'
      }
      return texts[category] || '未知'
    }
    
    const getStatusType = (status) => {
      const types = {
        'published': 'success',
        'draft': 'info',
        'reviewing': 'warning'
      }
      return types[status] || 'info'
    }
    
    const getStatusText = (status) => {
      const texts = {
        'published': '已发布',
        'draft': '草稿',
        'pending_review': '待审查',
        'desensitizing': '脱敏中',
        'manual_review': '人工审查',
        'reviewing': '审核中'
      }
      return texts[status] || '未知'
    }
    
    const getCaseEndTypeColor = (type) => {
      const colors = {
        'judgment': 'danger',
        'mediation': 'warning',
        'settlement': 'success',
        'withdrawal': 'info'
      }
      return colors[type] || 'info'
    }
    
    const getCaseEndTypeText = (type) => {
      const texts = {
        'judgment': '判决',
        'mediation': '调解',
        'settlement': '和解',
        'withdrawal': '撤诉'
      }
      return texts[type] || '未知'
    }
    
    const getSensitiveStatusType = (status) => {
      const types = {
        'desensitized': 'success',
        'pending_desensitization': 'warning'
      }
      return types[status] || 'danger'
    }
    
    const getSensitiveStatusText = (status) => {
      const texts = {
        'desensitized': '已脱敏',
        'pending_desensitization': '待脱敏'
      }
      return texts[status] || '未脱敏'
    }
    
    const handleSearch = () => {
      currentPage.value = 1
    }
    
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
    }
    
    const handleCurrentChange = (page) => {
      currentPage.value = page
    }
    
    const refreshData = () => {
      loading.value = true
      setTimeout(() => {
        loading.value = false
        alert('数据已刷新')
      }, 1000)
    }
    
    const editCase = (case_) => {
      alert(`编辑案例: ${case_.title}`)
    }
    
    const viewCase = (case_) => {
      alert(`预览案例: ${case_.title}`)
    }
    
    const deleteCase = (case_) => {
      if (confirm(`确定要删除案例 "${case_.title}" 吗？`)) {
        alert('删除成功')
      }
    }
    
    // 添加跳转到相关页面的方法
    const goToCaseReview = () => {
      // 跳转到案件审查流程页面
      window.open('/admin/case-review-process', '_blank')
    }
    
    const goToAutoDemo = () => {
      // 跳转到自动入库演示页面
      window.open('/admin/case-auto-demo', '_blank')
    }
    
    const manageVisibility = (case_) => {
      currentCase.value = case_
      showVisibilityDialog.value = true
    }
    
    const handleDesensitization = (case_) => {
      if (case_.sensitiveStatus === 'desensitized') {
        ElMessage.info(`案例"${case_.title}"已经完成脱敏处理`)
        return
      }
      
      ElMessageBox.confirm(
        `确定要对案例"${case_.title}"进行脱敏处理吗？此操作将自动隐藏或替换敏感信息。`,
        '脱敏处理确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        // 模拟脱敏处理
        case_.sensitiveStatus = 'desensitized'
        ElMessage.success('脱敏处理完成')
      }).catch(() => {
        ElMessage.info('已取消脱敏处理')
      })
    }
    
    const removeVisiblePerson = (person) => {
      if (currentCase.value) {
        const index = currentCase.value.visibleTo.indexOf(person)
        if (index > -1) {
          currentCase.value.visibleTo.splice(index, 1)
        }
      }
    }
    
    const saveVisibility = () => {
      if (currentCase.value && selectedPersons.value.length > 0) {
        // 添加新选择的人员，避免重复
        selectedPersons.value.forEach(person => {
          if (!currentCase.value.visibleTo.includes(person)) {
            currentCase.value.visibleTo.push(person)
          }
        })
        selectedPersons.value = []
        ElMessage.success('可见性设置已保存')
      }
      showVisibilityDialog.value = false
    }
    
    // 人工审查相关方法
    const handleManualReview = (case_) => {
      currentReviewCase.value = case_
      // 重置审查表单
      reviewForm.reviewResult = ''
      reviewForm.reviewComment = ''
      reviewForm.setAsRecommended = false
      reviewForm.allowPublicView = false
      reviewForm.revisionRequirements = []
      reviewForm.reviewer = '管理员' // 实际应用中应该从用户登录信息获取
      
      showManualReviewDialog.value = true
    }
    
    const submitReview = async () => {
      // 表单验证
      if (!reviewForm.reviewResult) {
        ElMessage.error('请选择审查结果')
        return
      }
      
      if (!reviewForm.reviewComment.trim()) {
        ElMessage.error('请输入审查意见')
        return
      }
      
      reviewSubmitting.value = true
      
      try {
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        const reviewTime = new Date().toLocaleString('zh-CN')
        
        // 创建审查记录
        const reviewRecord = {
          reviewTime,
          reviewer: reviewForm.reviewer,
          result: reviewForm.reviewResult,
          comment: reviewForm.reviewComment
        }
        
        // 添加到审查历史
        if (!currentReviewCase.value.reviewHistory) {
          currentReviewCase.value.reviewHistory = []
        }
        currentReviewCase.value.reviewHistory.unshift(reviewRecord)
        
        // 根据审查结果更新案例状态
        switch (reviewForm.reviewResult) {
          case 'approved':
            currentReviewCase.value.status = 'published'
            if (reviewForm.setAsRecommended) {
              currentReviewCase.value.isRecommended = true
            }
            if (reviewForm.allowPublicView) {
              if (!currentReviewCase.value.visibleTo.includes('所有律师')) {
                currentReviewCase.value.visibleTo.push('所有律师')
              }
            }
            ElMessage.success('案例审查通过，已发布到案例库')
            break
            
          case 'rejected':
            currentReviewCase.value.status = 'draft'
            ElMessage.warning('案例审查未通过，已退回草稿状态')
            break
            
          case 'needs_revision':
            currentReviewCase.value.status = 'manual_review'
            ElMessage.info('案例需要修改，已标记为人工审查状态')
            break
        }
        
        // 更新统计数据
        updateStatsAfterReview()
        
        showManualReviewDialog.value = false
        
      } catch (error) {
        console.error('提交审查结果失败:', error)
        ElMessage.error('提交审查结果失败，请重试')
      } finally {
        reviewSubmitting.value = false
      }
    }
    
    const updateStatsAfterReview = () => {
      // 重新计算统计数据
      const publishedCount = cases.value.filter(c => c.status === 'published').length
      const draftCount = cases.value.filter(c => c.status === 'draft').length
      const pendingReviewCount = cases.value.filter(c => c.status === 'pending_review').length
      
      stats.publishedCases = publishedCount
      stats.draftCases = draftCount
      stats.pendingReview = pendingReviewCount
    }
    
    return {
      loading,
      searchQuery,
      categoryFilter,
      statusFilter,
      tagFilter,
      sensitiveFilter,
      viewMode,
      currentPage,
      pageSize,
      showVisibilityDialog,
      currentCase,
      selectedPersons,
      showManualReviewDialog,
      currentReviewCase,
      reviewSubmitting,
      reviewForm,
      reviewRules,
      stats,
      cases,
      filteredCases,
      totalCases,
      getCategoryType,
      getCategoryText,
      getStatusType,
      getStatusText,
      getCaseEndTypeColor,
      getCaseEndTypeText,
      getSensitiveStatusType,
      getSensitiveStatusText,
      handleSearch,
      handleSizeChange,
      handleCurrentChange,
      refreshData,
      editCase,
      viewCase,
      deleteCase,
      goToCaseReview,
      goToAutoDemo,
      manageVisibility,
      handleDesensitization,
      removeVisiblePerson,
      saveVisibility,
      handleManualReview,
      submitReview,
      updateStatsAfterReview
    }
  }
}
</script>

<style scoped>
.case-library {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: bold;
  color: #1f2937;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-row {
  display: flex;
  gap: 16px;
  align-items: center;
}

.search-input {
  flex: 1;
  max-width: 400px;
}

.category-filter,
.status-filter {
  width: 120px;
}

.stats-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 16px;
  border-left: 4px solid #e5e7eb;
}

.stat-card.total {
  border-left-color: #3b82f6;
}

.stat-card.published {
  border-left-color: #10b981;
}

.stat-card.draft {
  border-left-color: #f59e0b;
}

.stat-card.views {
  border-left-color: #8b5cf6;
}

.stat-card.pending {
  border-left-color: #f59e0b;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  background: #f3f4f6;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: #6b7280;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #1f2937;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
  margin-top: 4px;
}

.cases-section {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  font-size: 20px;
  font-weight: bold;
  color: #1f2937;
  margin: 0;
}

.table-view {
  margin-bottom: 20px;
}

.case-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-text {
  flex: 1;
}

.cases-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.case-card {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 20px;
  background: #fafafa;
  transition: all 0.3s ease;
}

.case-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.case-card.recommended {
  border-left: 4px solid #f59e0b;
}

.case-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.case-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.case-id {
  font-size: 12px;
  color: #6b7280;
  font-weight: 500;
}

.case-status {
  display: flex;
  gap: 4px;
}

.case-content {
  margin-bottom: 16px;
}

.case-title {
  font-size: 16px;
  font-weight: bold;
  color: #1f2937;
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.case-summary {
  font-size: 14px;
  color: #6b7280;
  margin: 0 0 12px 0;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.case-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.tag-item {
  margin: 0;
}

.case-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 8px;
  margin-bottom: 16px;
  padding: 12px;
  background: white;
  border-radius: 6px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #6b7280;
}

.stat-item i {
  width: 12px;
}

.case-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.import-section {
  padding: 20px;
}

.upload-demo {
  width: 100%;
}

/* 可见性管理样式 */
.visibility-management {
  padding: 16px 0;
}

.case-info h4 {
  margin: 0 0 8px 0;
  color: #1f2937;
  font-size: 16px;
  font-weight: bold;
}

.case-meta {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.visibility-section,
.add-visibility {
  margin-bottom: 20px;
}

.visibility-section h5,
.add-visibility h5 {
  margin: 0 0 12px 0;
  color: #374151;
  font-size: 14px;
  font-weight: 600;
}

.current-visibility {
  min-height: 40px;
  padding: 8px;
  background: #f9fafb;
  border-radius: 6px;
  border: 1px dashed #d1d5db;
}

.visibility-tips {
  margin-top: 16px;
}

.visibility-tips ul {
  margin: 0;
  padding-left: 20px;
}

.visibility-tips li {
  margin-bottom: 4px;
  font-size: 13px;
  line-height: 1.4;
}

.visible-to {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.tag-filter,
.sensitive-filter {
  width: 120px;
}

/* 案例库说明区域样式 */
.library-info {
  background: white;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.library-info ol {
  margin: 12px 0 0 20px;
  padding: 0;
}

.library-info li {
  margin-bottom: 8px;
  line-height: 1.6;
  color: #374151;
}

.library-info p {
  margin: 0;
  line-height: 1.6;
}

.library-info .mt-2 {
  margin-top: 16px;
}

/* 人工审查对话框样式 */
.manual-review-container {
  max-height: 70vh;
  overflow-y: auto;
}

.review-case-info {
  background: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.review-case-info .case-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.review-case-info h3 {
  margin: 0;
  color: #1f2937;
  font-size: 18px;
  font-weight: 600;
  flex: 1;
  margin-right: 16px;
}

.review-case-info .case-meta {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.review-case-info .case-details p {
  margin: 8px 0;
  color: #4b5563;
  line-height: 1.6;
}

.review-form {
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.publish-settings {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.review-history {
  background: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
  margin-top: 20px;
}

.review-history h4 {
  margin: 0 0 16px 0;
  color: #1f2937;
  font-size: 16px;
  font-weight: 600;
}

.history-timeline {
  position: relative;
}

.history-item {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e5e7eb;
}

.history-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.history-time {
  min-width: 140px;
  color: #6b7280;
  font-size: 12px;
  padding-top: 2px;
}

.history-content {
  flex: 1;
}

.history-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.history-reviewer {
  font-weight: 600;
  color: #1f2937;
}

.history-comment {
  color: #4b5563;
  line-height: 1.6;
  background: white;
  padding: 12px;
  border-radius: 6px;
  border-left: 3px solid #3b82f6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .review-case-info .case-header {
    flex-direction: column;
    gap: 12px;
  }
  
  .history-item {
    flex-direction: column;
    gap: 8px;
  }
  
  .history-time {
    min-width: auto;
  }
}
</style> 